package cn.fintecher.pangolin.service.dataimp.service;

import cn.fintecher.pangolin.common.enums.Relationship;
import cn.fintecher.pangolin.common.enums.*;
import cn.fintecher.pangolin.common.exception.BadRequestException;
import cn.fintecher.pangolin.common.model.UploadFile;
import cn.fintecher.pangolin.common.model.*;
import cn.fintecher.pangolin.common.response.LoginResponse;
import cn.fintecher.pangolin.common.utils.InnerServiceUrl;
import cn.fintecher.pangolin.common.utils.SaxParseExcelUtil;
import cn.fintecher.pangolin.common.utils.ZWDateUtil;
import cn.fintecher.pangolin.entity.elastic.LeaveCaseModel;
import cn.fintecher.pangolin.entity.elastic.*;
import cn.fintecher.pangolin.service.dataimp.client.WebSocketClient;
import cn.fintecher.pangolin.service.dataimp.elastic.BaseCaseElastic;
import cn.fintecher.pangolin.service.dataimp.model.ImportCommonModel;
import cn.fintecher.pangolin.service.dataimp.model.WebSocketModel;
import cn.fintecher.pangolin.service.dataimp.repository.CaseInfoRepository;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.querydsl.core.BooleanBuilder;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.repository.ElasticsearchRepository;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Auther: xiaqun
 * @Description:
 * @Date: 10:55 2019/8/14
 */

@Service("baseService")
public class BaseService {
    @Autowired
    private RedisTemplate<String, Object> jsonRedisTemplate;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    WebSocketClient webSocketClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Value("${file.dir}")
    public String filePath;

    /**
     * 获取用户信息
     */
    public UserModel getUserByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response.getUserModel();
    }

    /***
     *上传路径
     * @param filePath
     * @return
     */
    public UploadFile getFileUrl(String filePath) {
        FileSystemResource resource = new FileSystemResource(filePath);
        MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
        param.add("file", resource);
        ResponseEntity<UploadFile> response = restTemplate.postForEntity(InnerServiceUrl.COMMON_SERVICE_UPLOADFILE, param, UploadFile.class);
        return response.getBody();
    }


    /**
     * 获取用户部门信息
     */
    public DepartmentModel getDepartmentByToken(String token) {
        LoginResponse response = (LoginResponse) jsonRedisTemplate.opsForValue().get(token);
        if (Objects.isNull(response)) {
            throw new BadRequestException(null, "user", "token.is.error");
        }
        return response.getDepartmentModel();
    }

    /**
     * 获取文件流
     */
    public InputStream getFile(String fileId) {
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> response = restTemplate.exchange(InnerServiceUrl.COMMON_SERVICE_GETFILEBYID.concat("/").concat(fileId),
                HttpMethod.GET, new HttpEntity<byte[]>(headers), byte[].class);
        List<String> content = response.getHeaders().get("Content-Disposition");
        if (Objects.isNull(content) || content.isEmpty()) {
            throw new BadRequestException(null, "file", "file.is.null");
        }
        if (!content.get(0).endsWith(SaxParseExcelUtil.EXCEL_TYPE_XLSX)) {
            throw new BadRequestException(null, "file", "file.format.error");
        }
        byte[] result = response.getBody();
        return new ByteArrayInputStream(result);
    }

    void sendMessageToOne(MessageType type, String title, String content, String userId) {
        try {
            WebSocketMessageModel webSocketMessageModel = new WebSocketMessageModel();
            webSocketMessageModel.setMessageType(type);
            webSocketMessageModel.setTitle(title);
            webSocketMessageModel.setContent(content);
            webSocketMessageModel.setMsgDate(ZWDateUtil.getNowDateTime());
            webSocketMessageModel.setMessageMode(MessageMode.POPUP);
            this.webSocketClient.sendMsgByUserId(webSocketMessageModel, userId);
        } catch (Exception var6) {
            var6.printStackTrace();
        }
    }

    /**
     * 获取输入文件流
     */
    public InputStream getFileIn(String name) throws FileNotFoundException {
        File file = new File(filePath + "/" + name);
        return new FileInputStream(file);
    }

    /**
     * 获取文件输出流
     */
    public OutputStream getFileOut(String name) throws FileNotFoundException {
        File file = new File(filePath + "/" + name);
        return new FileOutputStream(file);
    }

    /**
     * 获取文件对象
     */
    public UploadFile getUploadFile(String id) {
        ResponseEntity<UploadFile> entity = restTemplate.getForEntity("http://common-service/api/uploadFile/getUploadFile/" + id, UploadFile.class);
        return entity.getBody();
    }

    /**
     * 生成tet文件并返回文件ID
     */
    public String generateTxt(List<String> list, String butchNumber) {
        OutputStreamWriter osw = null;
        BufferedWriter bw;
        File file = null;
        try {
            //生成txt文件
            String path = "/home/temp/" + butchNumber + ".txt";
            file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            osw = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            bw = new BufferedWriter(osw);
            for (String s : list) {
                bw.write(s);
                bw.newLine();
            }
            bw.flush();
            //上传文件服务器
            FileSystemResource resource = new FileSystemResource(file);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource);
            ResponseEntity<UploadFile> entity = restTemplate.postForEntity("http://common-service/api/uploadFile/upload", param, UploadFile.class);
            if (entity.hasBody()) {
                UploadFile uploadFile = entity.getBody();
                return uploadFile.getId();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //删除临时文件
            if (Objects.nonNull(file)) {
                if (file.exists() && file.isFile()) {
                    File file1 = new File(file.getAbsolutePath());
                    file1.delete();
                }
            }
        }
    }

    /**
     * 生成tet文件并返回文件
     */
    public UploadFile generateTxtFile(List<String> list, String butchNumber) {
        OutputStreamWriter osw = null;
        BufferedWriter bw;
        File file = null;
        try {
            //生成txt文件
            String path = "/home/temp/" + butchNumber + ".txt";
            file = new File(path);
            if (!file.exists()) {
                file.getParentFile().mkdirs();
            }
            file.createNewFile();
            osw = new OutputStreamWriter(new FileOutputStream(file), StandardCharsets.UTF_8);
            bw = new BufferedWriter(osw);
            for (String s : list) {
                bw.write(s);
                bw.newLine();
            }
            bw.flush();
            //上传文件服务器
            FileSystemResource resource = new FileSystemResource(file);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource);
            ResponseEntity<UploadFile> entity = restTemplate.postForEntity("http://common-service/api/uploadFile/upload", param, UploadFile.class);
            if (entity.hasBody()) {
                return entity.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            //删除临时文件
            if (Objects.nonNull(file)) {
                if (file.exists() && file.isFile()) {
                    File file1 = new File(file.getAbsolutePath());
                    file1.delete();
                }
            }
        }
    }

    /**
     * 上传excel文件
     */
    public UploadFile uploadExcel(File file) {
        try {
            //上传文件服务器
            FileSystemResource resource = new FileSystemResource(file);
            MultiValueMap<String, Object> param = new LinkedMultiValueMap<>();
            param.add("file", resource);
            ResponseEntity<UploadFile> entity = restTemplate.postForEntity("http://common-service/api/uploadFile/upload", param, UploadFile.class);
            if (entity.hasBody()) {
                return entity.getBody();
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * @Author wangxiangdong
     * @Description 添加流转记录
     * @Date 2019/9/4 10:07
     **/
    public CaseTransferLog createCaseTranferLog(String caseId, String operContent, UserModel userModel, String outUserId, String inUserId, Double leftAmt) {
        CaseTransferLog caseTransferLog = new CaseTransferLog();
        caseTransferLog.setCaseId(caseId);
        caseTransferLog.setOperContent(operContent);
        caseTransferLog.setOutUserId(outUserId);
        caseTransferLog.setInUserId(inUserId);
        caseTransferLog.setLeftAmt(leftAmt);
        caseTransferLog.setUserName(userModel.getUsername());
        caseTransferLog.setFullName(userModel.getRealName());
        caseTransferLog.setOperatorTime(ZWDateUtil.getNowDateTime());
        return caseTransferLog;
    }

    /**
     * 生成任务盒子
     */
    public TaskBoxModel getTaskBox(TaskBoxType type, String description, UserModel userModel) {
        TaskBoxModel model = new TaskBoxModel();
        model.setId(UUID.randomUUID().toString().replaceAll("-", ""));
        sendTaskBoxMessage(model, type, TaskBoxStatus.UN_FINISH, null, null, userModel, ZWDateUtil.getNowDateTime(), null, description);
        return model;
    }

    public TaskBoxModel sendTaskBoxMessage(TaskBoxModel model, TaskBoxType taskBoxType, TaskBoxStatus taskBoxStatus,
                                           String fileId, String fileName, UserModel userModel, Date startTime, Date endTime, String taskDescribe) {
        model.setTaskBoxType(taskBoxType);
        model.setTaskBoxStatus(taskBoxStatus);
        model.setFileId(fileId);
        model.setFileName(fileName);
        model.setOperator(userModel.getId());
        model.setOperatorTime(ZWDateUtil.getNowDateTime());
        if (Objects.nonNull(taskDescribe)) {
            model.setTaskDescribe(taskDescribe);
        }
        if (Objects.nonNull(startTime)) {
            model.setBeginDate(startTime);
        }
        if (Objects.nonNull(endTime)) {
            model.setEndDate(endTime);
        }
        webSocketClient.sendTaskByUserId(model, userModel.getUsername());
        return model;
    }

    /**
     * 处理模板配置项
     *
     * @param items 模板配置项
     * @param index sheet页号
     * @return 有配置过的项, key为列号, value为配置项对象
     */
    public Map<String, ImportTemplateItem> processItem(List<ImportTemplateItem> items, Integer index) {
        //过滤sheet页为指定sheet页的配置
        List<ImportTemplateItem> list = items.stream().filter(e -> e.getSheetNumber().equals(index)).collect(Collectors.toList());
        Map<String, ImportTemplateItem> map = new HashMap<>();
        list.forEach(e -> {
            if (StringUtils.isNotBlank(e.getAttribute())) {
                map.put(e.getCol(), e);
            }
        });
        return map;
    }

    /**
     * 检验毕填配置项
     *
     * @param map 模板配置项集合
     * @return 错误字符串
     */
    public String validItem(Map<String, ImportTemplateItem> map, ImportTemplateType type) {
        boolean flag1 = false;
        boolean flag2 = false;
        boolean flag3 = false;
        switch (type) {
            case CASE_IMPORT:
                for (Map.Entry<String, ImportTemplateItem> entry : map.entrySet()) {
                    ImportTemplateItem item = entry.getValue();
                    switch (item.getAttribute()) {
                        case "name":  //客户姓名
                            flag1 = true;
                            break;
                        case "certificateNo":  //证件号
                            flag2 = true;
                            break;
                        case "caseNumber":  //案件编号
                            flag3 = true;
                            break;
                    }
                }
                if (!flag1) {
                    return "【客户姓名】没有对应的配置项";
                } else if (!flag2) {
                    return "【证件号】没有对应的配置项";
                } else if (!flag3) {
                    return "【案件编号】没有对应的配置项】";
                } else {
                    return null;
                }
            case CASE_UPDATE:
                for (Map.Entry<String, ImportTemplateItem> entry : map.entrySet()) {
                    ImportTemplateItem item = entry.getValue();
                    //案件编号
                    if ("caseNumber".equals(item.getAttribute())) {
                        flag3 = true;
                        break;
                    }
                }
                if (!flag3) {
                    return "【案件编号】没有对应的配置项】";
                } else {
                    return null;
                }
            case BILL_IMPORT:
                for (Map.Entry<String, ImportTemplateItem> entry : map.entrySet()) {
                    ImportTemplateItem item = entry.getValue();
                    switch (item.getAttribute()) {
                        case "caseNumber":  //案件编号
                            flag1 = true;
                            break;
                        case "paymentAmt":  //还款金额
                            flag2 = true;
                            break;
                        case "paymentDate":  //还款日期
                            flag3 = true;
                            break;
                    }
                }
                if (!flag1) {
                    return "【案件编号】没有对应的配置项";
                } else if (!flag2) {
                    return "【还款金额】没有对应的配置项";
                } else if (!flag3) {
                    return "【还款日期】没有对应的配置项】";
                } else {
                    return null;
                }
            case PRE_RECORD_IMPORT:
                for (Map.Entry<String, ImportTemplateItem> entry : map.entrySet()) {
                    ImportTemplateItem item = entry.getValue();
                    switch (item.getAttribute()) {
                        case "date":  //催记日期
                            flag1 = true;
                            break;
                        case "content":  //催记内容
                            flag2 = true;
                            break;
                        case "certificateNo":  //证件号
                            flag3 = true;
                            break;
                    }
                }
                if (!flag1) {
                    return "【催记日期】没有对应的配置项";
                } else if (!flag2) {
                    return "【催记内容】没有对应的配置项";
                } else if (!flag3) {
                    return "【证件号】没有对应的配置项】";
                } else {
                    return null;
                }
            default:
                return null;
        }
    }

    /**
     * excel行转对象
     */
    public void rowToObj(ImportCommonModel importCommonModel, Map.Entry<String, ImportTemplateItem> entry, Map<String, String> map, int row, List<String> errors, int sheetIndex) {
        ImportTemplateItem item = entry.getValue();
        String value = map.get(item.getCol());
        boolean b = false;
        if (item.getPropertyType().equals("CASE")) {
            if (importCommonModel.getFlag() == 0) {
                if (item.getAttribute().equals("caseNumber") || item.getAttribute().equals("overdueAmtTotal")) {
                    b = true;
                }
            } else {
                if (item.getAttribute().equals("caseNumber")) {
                    b = true;
                }
            }
            setValue(CaseImportModel.class, importCommonModel.getCaseImportModel(), item, errors, value, row, sheetIndex, b);
        } else if (item.getPropertyType().equals("PERSONAL")) {
            if (importCommonModel.getFlag() == 0) {
                if (item.getAttribute().equals("name") || item.getAttribute().equals("certificateNo")) {
                    b = true;
                }
            }
            setValue(PersonalImportModel.class, importCommonModel.getPersonalImportModel(), item, errors, value, row, sheetIndex, b);
        } else if (item.getPropertyType().equals("BILL")) {
            if (item.getAttribute().equals("caseNumber") || item.getAttribute().equals("paymentDate") || item.getAttribute().equals("paymentAmt")
                    || item.getAttribute().equals("type")) {
                b = true;
            }
            setValue(PaymentRecordModel.class, importCommonModel.getPaymentRecordModel(), item, errors, value, row, sheetIndex, b);
            importCommonModel.getPaymentRecordModel().process();
        } else if (item.getPropertyType().equals("FOLLOW")) {
            if (item.getAttribute().equals("certificateNo") || item.getAttribute().equals("date") || item.getAttribute().equals("content")) {
                b = true;
            }
            setValue(PreRecordModel.class, importCommonModel.getPreRecordModel(), item, errors, value, row, sheetIndex, b);
        } else if (item.getPropertyType().equals("WORK_ORDER")) {
            if (item.getAttribute().equals("caseNumber") || item.getAttribute().equals("date") || item.getAttribute().equals("content")) {
                b = true;
            }
            setValue(WorkOrderModel.class, importCommonModel.getWorkOrderModel(), item, errors, value, row, sheetIndex, b);
        } else if (item.getPropertyType().equals("WARNING")) {
            if (item.getAttribute().equals("caseNumber") || item.getAttribute().equals("content")) {
                b = true;
            }
            setValue(WarningModel.class, importCommonModel.getWarningModel(), item, errors, value, row, sheetIndex, b);
        } else if (item.getPropertyType().equals("LEAVE")) {
            if (item.getAttribute().equals("caseNumber") || item.getAttribute().equals("date")) {
                b = true;
            }
            setValue(LeaveCaseModel.class, importCommonModel.getLeaveCaseModel(), item, errors, value, row, sheetIndex, b);
        } else if (item.getPropertyType().equals("STOP")) {
            if (item.getAttribute().equals("caseNumber")) {
                b = true;
            }
            setValue(StopCaseModel.class, importCommonModel.getStopCaseModel(), item, errors, value, row, sheetIndex, b);
        }
        map.remove(item.getCol());
    }

    /**
     * 通过反射给字段赋值
     *
     * @param clazz      反射类
     * @param o          反射对象
     * @param item       模板配置项
     * @param errors     错误集合
     * @param value      赋值
     * @param row        excel行
     * @param sheetIndex sheet页编号
     * @param b          判断是否需要检查必填
     */
    private void setValue(Class<?> clazz, Object o, ImportTemplateItem item, List<String> errors, String value, int row, int sheetIndex, boolean b) {
        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            if (field.getName().equals(item.getAttribute())) {
                Object obj = checkValue(value, field, errors, row, item, sheetIndex, b);
                if (Objects.isNull(obj)) {
                    break;
                } else {
                    try {
                        PropertyDescriptor pd = new PropertyDescriptor(field.getName(), clazz);
                        Method method = pd.getWriteMethod();
                        method.invoke(o, obj);
                    } catch (IntrospectionException | InvocationTargetException | IllegalAccessException e) {
                        e.printStackTrace();
                        errors.add("第【" + sheetIndex + "】个sheet页中第【" + row + "】行表头为【" + item.getTitleName() + "】的数据反射错误");
                    }
                    break;
                }
            }
        }
    }

    /**
     * 判断excel值是否符合要求
     *
     * @param value      excel值
     * @param field      反射字段
     * @param errors     错误集合
     * @param row        excel行
     * @param item       模板配置项
     * @param sheetIndex sheet页编号
     * @param b          检查是否必传
     * @return 解析后的对象
     */
    private Object checkValue(String value, Field field, List<String> errors, int row, ImportTemplateItem item, int sheetIndex, boolean b) {
        Type type = field.getGenericType();
        if (b) {
//            if (StringUtils.isBlank(value)) {
//                errors.add("第【" + sheetIndex + "】个sheet页中第【" + row + "】行表头为【" + item.getTitleName() + "】的数据为空,请填写正确的数据");
//                return null;
//            }
        } else {
            if (StringUtils.isBlank(value)) {
                return null;
            }
        }
        if (type.equals(String.class)) { //字符串类型
            return value;
        } else if (type.equals(Integer.class)) { //数字类型
            try {
                return Integer.parseInt(value);
            } catch (Exception e) {
                errors.add("第【" + sheetIndex + "】个sheet页中第【" + row + "】行表头为【" + item.getTitleName() + "】的数据类型不是数字格式类型,正确格式为【0】");
                return null;
            }
        } else if (type.equals(Date.class)) { //日期类型
            try {
                return ZWDateUtil.getUtilDate(value);
            } catch (Exception e) {
                e.printStackTrace();
                errors.add("第【" + sheetIndex + "】个sheet页中第【" + row + "】行表头为【" + item.getTitleName() + "】的数据类型不是日期格式类型,正确格式为【1970-01-01】或者【1970/01/01】或者【19700101】");
                return null;
            }
        } else if (type.equals(Double.class)) { //浮点类型
            try {
                return Double.parseDouble(value);
            } catch (Exception e) {
                e.printStackTrace();
                errors.add("第【" + sheetIndex + "】个sheet页中第【" + row + "】行表头为【" + item.getTitleName() + "】的数据类型不是浮点格式类型,正确格式为【0.0】");
                return null;
            }
        }
        return null;
    }

    /**
     * 关系字符串转枚举类
     */
    public Relationship relationToEnum(String str) {
        if (Objects.nonNull(str)) {
            switch (str) {
                case "本人":
                    return Relationship.SELF;
                case "配偶":
                    return Relationship.SPOUSE;
                case "父母":
                    return Relationship.PARENT;
                case "家人":
                    return Relationship.CHILD;
                case "亲属":
                    return Relationship.RELATIVES;
                case "同事":
                    return Relationship.COLLEUAGUE;
                case "朋友":
                    return Relationship.FRIEND;
                case "其他":
                    return Relationship.OTHER;
                case "同学":
                    return Relationship.CLASSMATE;
                default:
                    return Relationship.OTHER;
            }
        } else {
            return null;
        }
    }

    /**
     * 地址类型字符串转枚举类
     */
    public AddressType addressTypeToEnum(String str) {
        if (Objects.nonNull(str)) {
            switch (str) {
                case "住宅地址":
                    return AddressType.HOUSE_ADDR;
                case "单位地址":
                    return AddressType.COMPANY_ADDR;
                case "户籍地址":
                    return AddressType.NATIVE_ADDR;
                case "邮寄地址":
                    return AddressType.BILL_ADDR;
                case "身份证地址":
                    return AddressType.IDCARD_ADDR;
                case "其他地址":
                    return AddressType.OTHER;
                default:
                    return AddressType.OTHER;
            }
        } else {
            return null;
        }
    }

    /**
     * 转化时间字符串
     */
    public Date transferDate(String dateStr) {
        return ZWDateUtil.getUtilDate(dateStr);
    }

    /**
     * 转化浮点数
     */
    public Double transferDouble(String doubleStr) {
        try {
            return Double.parseDouble(doubleStr);
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 复制excel模板
     */
    public void copyFile(InputStream in, File file) {
        FileOutputStream out = null;
        try {
            out = new FileOutputStream(file);
            byte[] buf = new byte[8 * 1024];
            int len = 0;
            while ((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                out.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            try {
                if (out != null) {
                    out.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 发送消息
     */
    public void sendMsg(MessageType type, UserModel userModel) {
        ObjectMapper mapper = new ObjectMapper();
        String messageString = null;
        WebSocketModel model = new WebSocketModel();
        model.setMessageType(type);
        try {
            messageString = mapper.writeValueAsString(model);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        rabbitTemplate.convertAndSend("oss", userModel.getId(), messageString);
    }

    /**
     * 检查案件是否存在
     */
    public boolean checkCase(String caseNumber, BaseCaseElastic baseCaseElastic, CaseInfoRepository caseInfoRepository) {
        BoolQueryBuilder builder = new BoolQueryBuilder();
        builder.must(QueryBuilders.matchPhraseQuery("caseNumber.keyword", caseNumber));
        Iterable<BaseCase> iterable = baseCaseElastic.search(builder);
        boolean a = iterable.iterator().hasNext();
        boolean b = caseInfoRepository.existsByCaseNumber(caseNumber);
        return a || b;
    }

    /**
     * 拼接es合规过滤条件
     */
    public void spliceBuilder(BoolQueryBuilder builder, UserModel userModel) {
        if (userModel.getIsCheck().equals(BaseSelect.YES)) {
            builder.must(QueryBuilders.termsQuery("principalId.keyword", userModel.getPrincipalIds()));
        }
    }
}
